<template>
  <div>
    <div class="wrap">
      <div class="title">收货信息</div>

      <div class="infoList" @click="jumpReciveAddrList" v-if="resAddressInfo">
        <div class="left">
          <div class="infoItem">
            <img src="@/assets/name.png" alt="" />
            <em>{{ resAddressInfo.nickName }}</em>
          </div>
          <div class="infoItem">
            <img src="@/assets/tel.png" alt="" />
            <em>{{ resAddressInfo.mobile }}</em>
          </div>
          <div class="infoItem">
            <img src="@/assets/addr2.png" alt="" />
            <em>{{ resAddressInfo.detailsAddress }}</em>
          </div>
        </div>
        <img src="@/assets/rightArrow.png" alt="" class="rightArrow" />
      </div>
      <div class="infoList" @click="jumpReciveAddrList" v-else>
        <div class="left" style="margin-bottom: 10px">请先设置收货地址</div>
        <img
          src="@/assets/rightArrow.png"
          alt=""
          class="rightArrow"
          style="margin-top: 5px"
        />
      </div>
      <div class="title">商品信息</div>
      <div class="proContainer">
        <div class="productListWrap">
          <div
            class="productItem"
            v-for="(item, index) in resCarGoodsList"
            :key="index"
          >
            <img
              :src="$imgUrl + item.listImgUrl"
              alt=""
              class="proPosterLeft"
            />
            <div class="proIntroRight2">
              <p class="proTitle2">{{ item.goodsName }}</p>
              <p class="saleNum2">{{ item.specsName }}</p>
              <div class="priceWrap2">
                <em class="price2">￥{{ item.totalPrice }}</em>
                <van-stepper
                  v-model="item.payNum"
                  theme="round"
                  button-size="18"
                  disable-input
                  min="0"
                  @change="onChange(item)"
                />
              </div>
            </div>
          </div>
          <div class="productItem" v-if="resCarGoodsList.length == 0">
            暂无商品
          </div>
          <div class="shopDiscounts" @click="show = true">
            <em class="shopDisTitle">店铺优惠</em>
            <em class="reduceRules" v-if="chooseCouponData"
              >满{{ chooseCouponData.thresholdPrice }}减{{
                chooseCouponData.discountsPrice
              }}</em
            >
            <em class="reduceRules" style="color: #999" v-else>暂无优惠</em>
            <img src="@/assets/rightArrow.png" alt="" class="rightImg" />
          </div>
          <div class="shopDiscounts">
            <em class="shopDisTitle">订单备注</em>
            <div class="inputNotes">
              <van-field
                v-model="notesInput"
                label=""
                placeholder="请输入备注(选填)"
                maxlength="30"
              />
            </div>
          </div>
          <div class="shopDiscounts">
            <em class="shopDisTitle"
              >本店配送费：<em class="transPrice">{{ transPrice }}元</em></em
            >
          </div>
        </div>
      </div>
    </div>
    <div style="height: 60px"></div>
    <div class="bottomWrap">
      <div class="total">共{{ carCountData.totalCount }}件</div>
      <div class="price">
        合计：<em>￥{{ carCountData.totalPrice }}</em>
      </div>
      <div class="sureSubmit" @click="crateOrder">确认提交</div>
    </div>
    <!-- 遮罩层-选择优惠券： -->
    <div class="maskWrap" v-if="show">
      <div class="maskBg" @click="show = false"></div>
      <div class="chooseNumWrap">
        <div class="discountsTitle">全部优惠</div>
        <div
          class="discountsItem"
          v-for="(item, index) in couponList"
          :key="index"
          @click="chooseCoupon(item)"
        >
          <div class="topBalck">店铺优惠券</div>
          <div class="disCountsMain">
            <div class="oneLeft"><em>￥</em>{{ item.discountsPrice }}</div>
            <div class="twoLeft">
              <div class="disPrice">满{{ item.thresholdPrice }}元可使用</div>
              <div class="date" v-if="item.outTime">
                有效期至{{ item.outTime }}
              </div>
              <div class="date" v-else>永久有效</div>
            </div>
            <img
              src="@/assets/check.png"
              alt=""
              class="threeLeft"
              v-if="chooseCouponData.id == item.id"
            />
            <img src="@/assets/noCheck.png" alt="" class="threeLeft" v-else />
          </div>
        </div>
        <div class="useDiscount">
          <van-checkbox
            v-model="checked"
            icon-size="16px"
            @change="checkNoUseCoupon"
            >不使用本次优惠</van-checkbox
          >
        </div>
        <div class="sureUseDiscount" @click="sureUse">确认使用</div>
      </div>
    </div>
    <!-- 遮罩层-确认提交 检测是否只支持本校配送弹窗提示： -->
    <!-- <div class="maskWrap" v-if="showSend">
      <div class="maskBg" @click="showSend = false"></div>
      <div class="chooseNumWrap2">
        <div class="sorry">抱歉！当前商品，仅支持本校区配送。</div>
        <div class="back">返回首页</div>
      </div>
    </div> -->
  </div>
</template>

<script>
import { Overlay, Stepper, Field, Checkbox } from "vant";
import {
  apiUserAddressList,
  apiGetCartGoodsList,
  apiShopCouponListByShopId,
  apiUpdateCartGoodsNum,
  apiCreateGoodsPreOrder,
  apiShopGoodsOrderPay,
  apiGetShopDetails,
  apiGetGoodsList,
  apiAddCartGoods,
  apiClearCartGoods,
  apiGetGoodsDetails,
} from "@/request/api"; // api接口
export default {
  name: "App",
  data() {
    return {
      value: "",
      notesInput: "",
      show: false,
      showSend: false,
      checked: false,
      reqShopId: this.$route.query.shopId, //店铺id
      chooseNewAddr: this.$route.query.chooseNewAddr, //重新选择的地址
      resCarGoodsList: [], //购物车列表数据
      carCountData: {
        totalCount: 0, //总件数
        totalPrice: 0, //总价格
      },
      resAddressInfo: "", //收货地址
      couponList: [], //优惠券
      chooseCouponData: "", //最终使用的优惠券数据
      orderNumber: "", //订单号
      resPayInfo: "",
    };
  },
  mounted() {
    console.log(this.$route.query);
    console.log(
      "校区信息",
      JSON.parse(sessionStorage.getItem("changeSchoolData"))
    );
    this.getShopDetails();
    this.getUserAddressList();
  },
  methods: {
    //用户收货地址列表：
    getUserAddressList() {
      apiUserAddressList({}).then((res) => {
        console.log(res);
        res.data.map((item) => {
          var name = sessionStorage.getItem("paySureAddrName");
          console.log("name", name);
          if (this.chooseNewAddr) {
            //编辑重新选择地址
            this.resAddressInfo = this.chooseNewAddr;
          }
          if (name == item.detailsAddress) {
            //编辑、新增地址
            console.log("ddddd");
            this.resAddressInfo = item;
            return;
          }
          if (item.status == 1) {
            //默认地址
            //查找默认地址
            this.resAddressInfo = item;
          }
        });
        console.log("收货地址", this.resAddressInfo);
      });
    },
    //获取店铺信息得到配送费
    getShopDetails() {
      apiGetShopDetails({
        id: this.reqShopId,
      }).then((res) => {
        console.log(res);
        this.transPrice = res.data.transPrice;
        this.getCartGoodsList();
        console.log("配送费", this.transPrice);
      });
    },
    //店铺优惠券列表：
    getShopCouponList() {
      this.chooseCouponData = "";
      apiShopCouponListByShopId({
        id: this.reqShopId,
      }).then((res) => {
        console.log(res);
        this.couponList = res.data;
        console.log("优惠券列表", this.couponList);
        for (var i = 0; i <= this.couponList.length; i++) {
          if (
            this.couponList[i].thresholdPrice <= this.carCountData.totalPrice
          ) {
            //符合满减规则
            if (
              i > 0 &&
              this.couponList[i].thresholdPrice >
                this.couponList[i - 1].thresholdPrice
            ) {
              //本次循环的减满金额更高
              this.chooseCouponData = this.couponList[i];
            } else {
              this.chooseCouponData = this.couponList[i];
            }
            console.log("frea", this.chooseCouponData);
            this.checked = false; //使用本次优惠
          }
          // console.log(this.carCountData.totalPrice );
          // console.log("选择的减满规则", this.chooseCouponData, i, this.couponList.length);
          // // this.carCountData.totalPrice = this.carCountData.totalPrice - this.chooseCouponData.discountsPrice; //减去优惠券的最终支付价格
          // // this.carCountData.totalPrice = this.carCountData.totalPrice.toFixed(2)
          // console.log(this.carCountData.totalPrice );
        }
      });
    },
    sureUse() {
      this.show = false;
    },
    //选择优惠券
    chooseCoupon(data) {
      if (data.thresholdPrice > this.carCountData.totalPrice) {
        this.$toast.fail("不符合满减条件");
      } else {
        this.checked = false;
        if (data.id != this.chooseCouponData.id) {
          this.carCountData.totalPrice =
            this.carCountData.totalPrice - data.discountsPrice; //减去优惠券的最终支付价格
          this.carCountData.totalPrice = this.carCountData.totalPrice.toFixed(
            2
          );
        }
        this.chooseCouponData = data;
      }
    },
    //勾选不使用优惠券：
    checkNoUseCoupon(value) {
      console.log("是否使用本次优惠券", value);
      this.chooseCouponData = "";
      this.carCountData.totalCount = 0;
      this.carCountData.totalPrice = 0;
      apiGetCartGoodsList({
        id: this.reqShopId,
      }).then((res) => {
        this.resCarGoodsList = res.data;
        this.resCarGoodsList.map((item) => {
          this.carCountData.totalCount =
            this.carCountData.totalCount + item.payNum;
          this.carCountData.totalPrice =
            this.carCountData.totalPrice + item.totalPrice;
        });
        this.carCountData.totalPrice =
          this.carCountData.totalPrice + this.transPrice;
        this.carCountData.totalPrice = this.carCountData.totalPrice.toFixed(2);
        console.log(typeof this.carCountData.totalPrice);
      });
    },
    //请求购物车列表：
    getCartGoodsList() {
      this.carCountData.totalCount = 0;
      this.carCountData.totalPrice = 0;
      apiGetCartGoodsList({
        id: this.reqShopId,
      }).then((res) => {
        console.log(res);
        this.resCarGoodsList = res.data;
        this.resCarGoodsList.map((item) => {
          this.carCountData.totalCount =
            this.carCountData.totalCount + item.payNum;
          this.carCountData.totalPrice =
            this.carCountData.totalPrice + item.totalPrice;
        });
        this.carCountData.totalPrice =
          this.carCountData.totalPrice + this.transPrice;
        console.log(this.carCountData.totalPrice);
        this.carCountData.totalPrice = Number(
          this.carCountData.totalPrice.toFixed(2)
        );
        console.log("购物车数据", this.resCarGoodsList);

        this.getShopCouponList();
        // setTimeout(() => {
        //   this.carCountData.totalPrice = this.carCountData.totalPrice - this.chooseCouponData.discountsPrice; //减去优惠券的最终支付价格
        // }, 2000);
      });
    },
    //修改购物车的数量：
    onChange(data) {
      console.log("修改购物车的数据", data);
        apiUpdateCartGoodsNum({
          goodsId: data.goodsId,
          payNum: data.payNum,
          shopId: data.shopId,
          specsId: data.specsId,
        }).then((res) => {
          console.log(res);
          this.getCartGoodsList();
        });
    },
    //确认提交订单：
    crateOrder() {
      // 当前店铺所在校区:
      var whereShopSchool = JSON.parse(
        sessionStorage.getItem("changeSchoolData")
      ).schoolIName;
      if (this.resAddressInfo.schoolName == whereShopSchool) {
        apiCreateGoodsPreOrder({
          addressId: this.resAddressInfo.id,
          couponId: this.chooseCouponData ? this.chooseCouponData.id : "",
          shopId: this.reqShopId,
          orderRemark: this.notesInput,
        }).then((res) => {
          console.log("创建订单获取订单id", res.data);
          this.orderNumber = res.data.orderNum;
          this.getUserEnterOrderPay();
        });
      } else {
        this.$toast.fail("抱歉！当前商品，仅支持本校区配送。");
      }
    },
    //根据订单id获取微信支付需要的信息
    getUserEnterOrderPay() {
      apiShopGoodsOrderPay({
        orderNum: this.orderNumber,
      }).then((res) => {
        if (res.code == 200) {
          this.resPayInfo = res.data;
          console.log("微信支付相关信息", this.resPayInfo);
          this.onBridgeReady();
        }
      });
    },
    //调起微信支付：
    onBridgeReady() {
      // alert("sign:", this.resPayInfo.sign);
      var that = this;
      console.log("that.resPayInfo", that.resPayInfo);
      WeixinJSBridge.invoke(
        "getBrandWCPayRequest",
        {
          appId: that.resPayInfo.appId, //公众号ID，由商户传入
          timeStamp: that.resPayInfo.timeStamp, //时间戳，自1970年以来的秒数
          nonceStr: that.resPayInfo.nonceStr, //随机串
          package: that.resPayInfo.package,
          signType: that.resPayInfo.signType, //微信签名方式：
          paySign: that.resPayInfo.sign, //微信签名
        },
        function (res) {
          if (res.err_msg == "get_brand_wcpay_request:ok") {
            that.$toast.success("支付成功");
            // 使用以上方式判断前端返回,微信团队郑重提示：
            //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
            that.$router.push({
              path: "/pages/shopInfo",
              query: {
                //传递参数
                shopId: that.reqShopId,
              },
            });
          }
        }
      );
    },
    //编辑收货地址：
    jumpReciveAddrList() {
      this.$router.push({
        path: "/pages/reciveAddrList",
        query: {
          //传递参数
          formId: 0,
          shopId: this.reqShopId,
        },
      });
    },
  },
  created() {},
  destroyed() {
    sessionStorage.removeItem("paySureAddrName");
  },
  components: {
    [Overlay.name]: Overlay,
    [Stepper.name]: Stepper,
    [Field.name]: Field,
    [Checkbox.name]: Checkbox,
  },
};
</script>

<style scoped>
.wrap {
  background: #f2f4fa;
  padding: 15px;
  min-height: calc(100vh - 70px);
}
.title {
  font-size: 13px;
  font-weight: 400;
  color: #999999;
  margin: 9px 0px;
}
.infoList {
  overflow: hidden;
  width: calc(100% - 30px);
  background: #ffffff;
  border-radius: 20px;
  padding: 15px 15px 5px 15px;
  margin-bottom: 20px;
}
.left {
  float: left;
}
.infoItem {
  height: 20px;
  line-height: 20px;
  display: flex;
  margin-bottom: 15px;
}
.infoItem img {
  width: 17px;
  height: auto;
  align-items: center;
  padding-right: 15.5px;
}
.infoItem em {
  font-size: 14px;
  font-weight: 400;
  color: #000000;
}
.rightArrow {
  float: right;
  width: 5px;
  height: 9px;
  margin-top: 40px;
}
.proContainer {
  background-color: gold;
  width: calc(100% - 30px);
  background: #ffffff;
  border-radius: 20px;
  padding: 15px 15px 5px 15px;
  margin-bottom: 20px;
}
.productListWrap {
}
.productItem {
  overflow: hidden;
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}
.proPosterLeft {
  width: 24%;
  height: 75px;
}
.proIntroRight2 {
  width: 70%;
}
.proTitle2 {
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-top: 0px;
}
.saleNum2 {
  margin-top: 9px;
  font-size: 10px;
  font-weight: 300;
  color: #666666;
  text-align: left;
  margin-bottom: 0px;
}
.priceWrap2 {
  margin-top: 4px;
  display: flex;
  justify-content: space-between;
}
.price2 {
  font-size: 10px;
  font-weight: bold;
  color: #ff4646;
}
/deep/.van-stepper--round .van-stepper__plus {
  background-color: #f48f5b;
}
/deep/.van-stepper--round .van-stepper__minus {
  border-color: #f48f5b;
  color: #f48f5b;
  background-color: #fff;
}
.shopDiscounts {
  border-top: 1px solid #eeeeee;
  height: 45px;
  line-height: 45px;
}
.shopDisTitle {
  font-size: 13px;
  font-weight: 400;
  color: #000000;
  float: left;
}
.transPrice {
  color: #ff4646;
}
.reduceRules {
  font-size: 13px;
  font-weight: 400;
  color: #f48f5b;
  float: left;
  margin-left: 20px;
}
.rightImg {
  float: right;
  width: 5px;
  height: 9px;
  margin-top: 19px;
}

.inputNotes {
  width: 80%;
  float: left;
}
.van-cell {
  background-color: none;
}
.bottomWrap {
  width: 100%;
  height: 70px;
  line-height: 70px;
  background: #ffffff;
  box-shadow: 0px 3px 12px 0px rgba(0, 0, 0, 0.12);
  border-radius: 20px 20px 0px 0px;
  position: fixed;
  bottom: 0px;
}

.total {
  float: left;
  font-size: 13px;
  color: #000000;
  margin-left: 15px;
  margin-top: 3px;
}

.price {
  float: left;
  font-size: 13px;
  color: #000000;
  margin-left: 30px;
}

.price em {
  color: #ff4646;
  font-size: 20px;
}

.sureSubmit {
  float: right;
  margin-right: 15px;
  width: 95px;
  height: 34px;
  line-height: 34px;
  background: #181818;
  border-radius: 17px;
  font-size: 14px;
  font-weight: 500;
  color: #ffffff;
  margin-top: 15px;
  text-align: center;
}
.maskWrap {
}
.maskBg {
  width: 100%;
  min-height: 100vh;
  opacity: 0.35;
  background-color: #000;
  position: fixed;
  top: 0px;
}
.chooseNumWrap {
  width: 100%;
  background-color: #fff;
  position: fixed;
  bottom: 0px;
  max-height: 540px;
  border-radius: 20px 20px 0px 0px;
  overflow: auto;
}

.discountsTitle {
  font-size: 15px;
  font-weight: 500;
  color: #000000;
  text-align: center;
  margin: 25px 0px;
}
.discountsItem {
  width: 90%;
  margin: 0 auto;
  height: 98px;
  background: #f2f4fa;
  border-radius: 15px;
  margin-bottom: 15px;
}
.topBalck {
  width: 90px;
  height: 20px;
  line-height: 20px;
  background: #181818;
  border-radius: 13px 0px 13px 0px;
  font-size: 12px;
  font-weight: 400;
  color: #ffffff;
  text-align: center;
}

.disCountsMain {
  overflow: hidden;
  margin-top: 20px;
}

.oneLeft {
  color: #ff4646;
  font-size: 20px;
  float: left;
  margin-left: 25px;
  margin-right: 35px;
  margin-top: 10px;
}

.oneLeft em {
  font-size: 12px;
}
.twoLeft {
  float: left;
}
.disPrice {
  font-size: 12px;
  font-weight: 500;
  color: #000000;
}
.date {
  font-size: 10px;
  font-weight: 400;
  color: #666666;
  margin-top: 10px;
}
.threeLeft {
  float: right;
  width: 25px;
  margin-right: 30px;
}
.useDiscount {
  margin-left: 20px;
  font-size: 12px;
  font-weight: 400;
  color: #000000;
}
.sureUseDiscount {
  width: 90%;
  height: 50px;
  line-height: 50px;
  background: #181818;
  box-shadow: 0px 5px 20px 0px rgba(24, 24, 24, 0.26);
  border-radius: 25px;
  font-size: 16px;
  font-weight: 500;
  color: #ffffff;
  text-align: center;
  margin: 30px auto;
}
.chooseNumWrap2 {
  width: 90%;
  left: 5%;
  background-color: #fff;
  position: fixed;
  top: 40vh;
  border-radius: 20px;
}
.sorry {
  font-size: 14px;
  font-weight: 500;
  color: #666666;
  text-align: center;
  margin-top: 35px;
}
.back {
  width: 115px;
  height: 34px;
  line-height: 34px;
  text-align: center;
  background: #181818;
  border-radius: 17px;
  font-size: 14px;
  font-weight: bold;
  color: #ffffff;
  margin: 20px auto;
}
</style>
